<template>
  <div class="chat-container">
    <!-- 聊天消息显示区域 -->
    <div class="chat-messages">
      <div v-for="(message, index) in chatMessages" :key="index" class="chat-message">
        {{ message }}
      </div>
    </div>
    <!-- 消息输入框和发送按钮 -->
    <div class="chat-input">
      <input
        v-model="newMessage"
        type="text"
        placeholder="请输入消息..."
        @keyup.enter="sendMessage"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

// 定义聊天消息数组，用于存储所有的聊天记录
const chatMessages = ref([]);
// 定义新消息变量，用于绑定输入框的值
const newMessage = ref('');

// 发送消息的方法
const sendMessage = () => {
  if (newMessage.value.trim()!== '') {
    // 将新消息添加到聊天消息数组中
    chatMessages.value.push(newMessage.value);
    axios.post('http://127.0.0.1:7001', { msg: newMessage.value }).then(res =>{
        console.log(res.data);
        chatMessages.value.push(res.data);
    })
    // 清空输入框
    newMessage.value = '';
  }
};
</script>

<style scoped>
.chat-container {
  width: 300px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
}

.chat-messages {
  height: 200px;
  overflow-y: auto;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}

.chat-message {
  margin-bottom: 5px;
}

.chat-input {
  display: flex;
}

.chat-input input {
  flex: 1;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.chat-input button {
  margin-left: 5px;
  padding: 5px 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #0056b3;
}
</style>